package com.fc.mall.portal.service.impl;

import com.fc.mall.base.object.Result;
import com.fc.mall.exception.ServiceException;
import com.fc.mall.mapper.*;
import com.fc.mall.model.*;
import com.fc.mall.mapper.*;
import com.fc.mall.portal.config.WspConfig;
import com.fc.mall.portal.dao.PortalOrderBuyDao;
import com.fc.mall.portal.domain.CartPromotionItem;
import com.fc.mall.portal.domain.ConfirmOrderResult;
import com.fc.mall.portal.domain.ImmediatelyGroupOrderParam;
import com.fc.mall.portal.domain.OrderParam;
import com.fc.mall.portal.dto.OmsGroupCartItem;
import com.fc.mall.portal.dto.OmsOrderGroupBuyDto;
import com.fc.mall.portal.dto.OrderGroupParam;
import com.fc.mall.portal.service.*;
import com.fc.mall.portal.wechat.WxPay;
import com.fc.mall.portal.wechat.dto.WxConfig;
import com.fc.mall.util.Constants;
import com.fc.mall.util.DateTimeHelper;
import com.fc.mall.util.Utils;
import com.fc.mall.model.*;
import com.fc.mall.portal.service.*;
import ma.glasnost.orika.MapperFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by sunny on 2019/8/19.
 */
@Service
public class OmsOrderGroupServiceImpl implements OmsOrderGroupService {

     @Autowired
     private UmsMemberService memberService;

    @Autowired
    private MapperFacade mapperFacade;

    @Autowired
    private UmsMemberReceiveAddressService memberReceiveAddressService;

    @Autowired
    private OmsPortalOrderService portalOrderService;

    @Autowired
    private OmsOrderItemMapper orderItemMapper;

    @Autowired
    private PmsProductGroupBuyMapper productGroupBuyMapper;

    @Autowired
    private OmsOrderGroupBuyMapper orderGroupBuyMapper;

    @Autowired
    private OmsOrderGroupBuyItemMapper orderGroupBuyItemMapper;

    @Autowired
    private PmsSkuStockMapper skuStockMapper;

    @Autowired
    private OmsOrderMapper orderMapper;

    @Autowired
    private WxConfig wxConfig;

    @Autowired
    private WspConfig wspConfig;

    @Autowired
    private RedisService redisService;

    @Autowired
    private ConfigService configService;

    @Autowired
    private PortalOrderBuyDao portalOrderBuyDao;

    @Autowired
    private SmsService smsService;


    @Override
    public ConfirmOrderResult generateConfirmGroupOrder(OmsGroupCartItem omsCartItem) {
        ConfirmOrderResult orderResult = new ConfirmOrderResult();

        /**
         * 如果是参团的订单这里要赋当前团购的ID
         */
        if(null != omsCartItem.getOrderGroupId())
        {
            orderResult.setOrderGroupId(omsCartItem.getOrderGroupId());
        }

        CartPromotionItem promotionItem = new CartPromotionItem();
        mapperFacade.map(omsCartItem, promotionItem);
        List<CartPromotionItem> itemList = new ArrayList<>();
        itemList.add(promotionItem);
        orderResult.setCartPromotionItemList(itemList);
        List<UmsMemberReceiveAddress> memberReceiveAddressList = memberReceiveAddressService.list();
        orderResult.setMemberReceiveAddressList(memberReceiveAddressList);

        ConfirmOrderResult.CalcAmount calcAmount = calcCartAmount(promotionItem);
        orderResult.setCalcAmount(calcAmount);
        return orderResult;
    }

    @Override
    public Result generateGroupOrder(ImmediatelyGroupOrderParam immediatelyOrderParam) {
        OmsGroupCartItem groupCartItem = immediatelyOrderParam.getOmsCartItem();
        OrderParam orderParam = immediatelyOrderParam.getOrderParam();
        UmsMember currentMember = memberService.getCurrentMember();

        PmsProductGroupBuy pmsProductGroupBuy = productGroupBuyMapper.selectByPrimaryKey(groupCartItem.getProductGroupId());

        if(null == pmsProductGroupBuy)
        {
            throw new ServiceException("当前团购不存在");
        }

        /**
         * 生成订单
         */
        OmsOrderItem orderItem = buildGroupOrderItem(groupCartItem);
        BigDecimal totalAmount = orderItem.getProductPrice().multiply(new BigDecimal(orderItem.getProductQuantity())).setScale(2);
        OmsOrder order = buildGroupOrder(currentMember, orderParam, totalAmount);
        //插入order表和order_item表
        orderMapper.insert(order);
        orderItem.setOrderId(order.getId());
        orderItem.setOrderSn(order.getOrderSn());
        orderItemMapper.insert(orderItem);
        OmsOrderGroupBuy orderGroupBuy;
        if(null == orderParam.getOrderGroupId())
        {
           orderGroupBuy = insertOrderGroupBuy(groupCartItem.getProductGroupId(), order, orderItem, currentMember, pmsProductGroupBuy);
        }
        else
        {
            orderGroupBuy =updateOrderGroupBuy(orderParam.getOrderGroupId(), order, currentMember, pmsProductGroupBuy);
        }

        Map<String,Object> result = new HashMap<>();
        result.put("order",order);
        result.put("orderGroupId", orderGroupBuy.getId());
        return Result.success("下单成功", result);
    }

    @Override
    public OmsOrderGroupBuyDto getOwnerGroupOrder(Long groupId, Long groupOrderId) {
        UmsMember currentMember = memberService.getCurrentMember();
        OmsOrderGroupBuyDto omsOrderGroupBuyDto = new OmsOrderGroupBuyDto();
        OmsOrderGroupBuy orderGroupBuy;
        if(groupOrderId.intValue() == 0)
        {

            OmsOrderGroupBuyExample buyExample = new OmsOrderGroupBuyExample();
            buyExample.createCriteria().andProductGroupIdEqualTo(groupId).andOwnerIdEqualTo(currentMember.getId()).andStatusEqualTo(1);
            List<OmsOrderGroupBuy> orderGroupBuyList = orderGroupBuyMapper.selectByExample(buyExample);
            if(null == orderGroupBuyList || orderGroupBuyList.isEmpty())
            {
                throw new ServiceException("该团购不存在");
            }
            orderGroupBuy = orderGroupBuyList.get(0);
        }
        else
        {
            orderGroupBuy =  orderGroupBuyMapper.selectByPrimaryKey(groupOrderId);
            if(null == orderGroupBuy)
            {
                throw new ServiceException("该团购不存在");
            }
        }


        mapperFacade.map(orderGroupBuy, omsOrderGroupBuyDto);
        omsOrderGroupBuyDto.setCurrentMemberId(currentMember.getId());

        OmsOrderGroupBuyItemExample buyItemExample = new OmsOrderGroupBuyItemExample();
        buyItemExample.createCriteria().andOmsOrderGroupBuyIdEqualTo(orderGroupBuy.getId());
        buyItemExample.setOrderByClause("create_time asc");
        List<OmsOrderGroupBuyItem>  orderGroupBuyItemList = orderGroupBuyItemMapper.selectByExample(buyItemExample);
        List<OmsOrderGroupBuyItem> filterList = orderGroupBuyItemList.stream().filter(item -> item.getStatus().intValue() == 1).collect(Collectors.toList());
        for(OmsOrderGroupBuyItem item : filterList)
        {
            if(item.getMemberId().equals(currentMember.getId()))
            {
                omsOrderGroupBuyDto.setHasJoinGroup(true);
            }
            item.setNickname(Utils.urlDecoderTransfer(item.getNickname()));
            if(StringUtils.isEmpty(item.getIcon()))
            {
                item.setIcon("https://dobuymall.oss-cn-shanghai.aliyuncs.com/wxapplet/icon/user-heard-icon.png");
            }
            if(item.getMemberId().equals(currentMember.getId()))
            {
                omsOrderGroupBuyDto.setCurrentMemberOrderId(item.getOrderId());
            }
            if(null != item.getCreateTime())
            {
                item.setCreateTimeTxt(DateTimeHelper.getEpochTimeToString(item.getCreateTime(), DateTimeHelper.SQL_DATETIME));
            }
        }
        omsOrderGroupBuyDto.getGroupBuyItemList().addAll(filterList);
        return omsOrderGroupBuyDto;
    }

    @Override
    public synchronized boolean handleOrderGroupPaySuccess(Long orderId) {
        OmsOrderGroupBuyItemExample omsOrderGroupBuyItemExample = new OmsOrderGroupBuyItemExample();
        omsOrderGroupBuyItemExample.createCriteria().andOrderIdEqualTo(orderId);
        List<OmsOrderGroupBuyItem> orderGroupBuyItemList = orderGroupBuyItemMapper.selectByExample(omsOrderGroupBuyItemExample);
        if(null == orderGroupBuyItemList || orderGroupBuyItemList.isEmpty())
        {
            return false;
        }
        OmsOrderGroupBuyItem orderGroupBuyItem = orderGroupBuyItemList.get(0);
        orderGroupBuyItem.setStatus(1);
        orderGroupBuyItemMapper.updateByPrimaryKeySelective(orderGroupBuyItem);
        OmsOrderGroupBuy orderGroupBuy = orderGroupBuyMapper.selectByPrimaryKey(orderGroupBuyItem.getOmsOrderGroupBuyId());

        Integer currentCount = orderGroupBuy.getMemberCount()+1;

        OmsOrderGroupBuy update = new OmsOrderGroupBuy();
        update.setId(orderGroupBuy.getId());
        update.setMemberCount(currentCount);
        /**
         *  团长发起拼团
         *  - 更改团的状态从0到1
         */
        if(orderGroupBuy.getOwnerId().equals(orderGroupBuyItem.getMemberId()))
        {
            PmsProductGroupBuy productGroupBuy = productGroupBuyMapper.selectByPrimaryKey(orderGroupBuy.getProductGroupId());
            int activeSecond = productGroupBuy.getActiveHour() * 60;
            update.setStatus(1);
            update.setExpiredTime(DateTimeHelper.getEpochTimeInSecond(System.currentTimeMillis()) + activeSecond);
            String groupOrderKey = wspConfig.appName + "orderGroup-" + orderGroupBuy.getId();
            redisService.set(groupOrderKey, orderGroupBuy.getId().toString());
            redisService.expire(groupOrderKey, activeSecond);
        }
        /**
         * 参团
         * 1.没满团： 更新团人数。更新
         * 2.满团：更新人数。更新状态
         */
        else
        {
            PmsProductGroupBuy productGroupBuy = productGroupBuyMapper.selectByPrimaryKey(orderGroupBuy.getProductGroupId());

            Integer groupCount = productGroupBuy.getGroupCount();
            // 满团情况
            System.out.println("============groupCount=="+groupCount+ "===============currentCount="+currentCount+"==============================================");
            if(groupCount.equals(currentCount))
            {
                update.setStatus(2);
                int totalCount = productGroupBuy.getTotalCount() + productGroupBuy.getGroupCount();
                productGroupBuy.setTotalCount(totalCount);
                productGroupBuyMapper.updateByPrimaryKeySelective(productGroupBuy);
                inActiveNoPaymentOrder(update.getId());

                //拼团成功发送消息
                //拼接成员名称
                OmsOrderGroupBuyItemExample omsOrderGroupBuyItemExample2 = new OmsOrderGroupBuyItemExample();
                omsOrderGroupBuyItemExample2.createCriteria().andOmsOrderGroupBuyIdEqualTo(orderGroupBuy.getId());
                List<OmsOrderGroupBuyItem> orderGroupBuyItemList2 = orderGroupBuyItemMapper.selectByExample(omsOrderGroupBuyItemExample2);
                System.out.println("===============开始发送消息==" + orderGroupBuyItemList2.size() + "============================");
                StringBuilder  associatesBuilder = new StringBuilder();
                for (OmsOrderGroupBuyItem item : orderGroupBuyItemList2)
                {
                    associatesBuilder.append(Utils.urlDecoderTransfer(item.getNickname())).append("、");
                }

                String associates = associatesBuilder.toString();
                if(!StringUtils.isEmpty(associates)) {
                    associates = associates.substring(0, associates.length()-1);
                }
                for(OmsOrderGroupBuyItem item : orderGroupBuyItemList2)
                {
                    smsService.sendGroupPurchaseSuccess(item.getMemberId(),
                            orderGroupBuy.getProductName(),
                            groupCount,
                            Utils.urlDecoderTransfer(orderGroupBuy.getNickname()),
                            orderGroupBuy.getSkuPrice().setScale(2),
                            orderGroupBuy.getGroupPrice().setScale(2),
                            associates);
                }
            }
            else if(groupCount.intValue() < currentCount )
            {
                orderGroupBuyItem.setStatus(0);

                orderGroupBuyItemMapper.updateByPrimaryKeySelective(orderGroupBuyItem);
                OmsOrder omsOrder = orderMapper.selectByPrimaryKey(orderId);
                refundForCancelOrder(omsOrder);

                //拼团失败发送通知
                String startTime = DateTimeHelper.getEpochTimeToString(orderGroupBuy.getCreateTime(), DateTimeHelper.SQL_DATETIME);
                String reason = "团购人数已满";
                String tipMsg = "很遗憾，有效期内未能成团。爱拼才会赢，再拼一次";
                smsService.sendGroupPurchaseFaild(omsOrder.getMemberId(), orderGroupBuy.getProductName(), startTime,
                        orderGroupBuy.getGroupPrice(), orderGroupBuy.getMemberCount(), reason, omsOrder.getOrderSn(), tipMsg);
            }
            else {
                update.setStatus(1);
            }
        }


        orderGroupBuyMapper.updateByPrimaryKeySelective(update);
        return true;
    }

    @Override
    public void cancelGroupOrder(String expiredKey) {

        System.out.println("退款过期的key:" + expiredKey);
        if(!expiredKey.contains(wspConfig.appName + "orderGroup"))
        {
            return;
        }
        String value = expiredKey.split("-")[1];
        OmsOrderGroupBuy orderGroupBuy = orderGroupBuyMapper.selectByPrimaryKey(Long.valueOf(value));

        if(null == orderGroupBuy || orderGroupBuy.getStatus() == OrderGroupStatus.COMPLATED.value)
        {
            return;
        }
        OmsOrderGroupBuyItemExample buyItemExample = new OmsOrderGroupBuyItemExample();
        buyItemExample.createCriteria().andOmsOrderGroupBuyIdEqualTo(orderGroupBuy.getId());
        List<OmsOrderGroupBuyItem> groupBuyItemList = orderGroupBuyItemMapper.selectByExample(buyItemExample);
        if(null == groupBuyItemList ||  groupBuyItemList.isEmpty())
        {
            orderGroupBuyMapper.deleteByPrimaryKey(orderGroupBuy.getId());
        }

        List<Long> orderIdList = new ArrayList<>();
        for(OmsOrderGroupBuyItem item : groupBuyItemList)
        {
            orderIdList.add(item.getOrderId());
        }

        OmsOrderExample orderExample = new OmsOrderExample();
        orderExample.createCriteria().andIdIn(orderIdList).andStatusEqualTo(OrderGroupStatus.INPROGESS_ORDER.value);
        List<OmsOrder> orderList = orderMapper.selectByExample(orderExample);
        for(OmsOrder order : orderList)
        {
            refundForCancelOrder(order);

            //拼团失败发送通知
            String startTime = DateTimeHelper.getEpochTimeToString(orderGroupBuy.getCreateTime(), DateTimeHelper.SQL_DATETIME);
            String reason = "拼团失败";
            String tipMsg = "很遗憾，有效期内未能成团。爱拼才会赢，再拼一次";
            smsService.sendGroupPurchaseFaild(order.getMemberId(), orderGroupBuy.getProductName(), startTime,
                    orderGroupBuy.getGroupPrice(), orderGroupBuy.getMemberCount(), reason, order.getOrderSn(), tipMsg);
        }

        orderGroupBuy.setStatus(OrderGroupStatus.INACTIVE.value);
        orderGroupBuyMapper.updateByPrimaryKeySelective(orderGroupBuy);


    }


    private void refundForCancelOrder(OmsOrder order)
    {
        WxPay wxPay = new WxPay(wxConfig);
        String isDebugStr = configService.getOptionalConfig(Constants.SysPropertyConfigName.PAYMENTDEBUG.getName(), "0");
        boolean isDebug = isDebugStr.equals("1");
        wxConfig.setDebug(isDebug);
        String refundNo = wspConfig.appName + DateTimeHelper.getStringFromDate(new Date(), DateTimeHelper.PLAIN_DATETIME);
        int totalFee = order.getPayAmount().multiply(new BigDecimal(100)).intValue();
        int refundFee = order.getPayAmount().multiply(new BigDecimal(100)).intValue();
        if(wxConfig.isDebug())
        {
            totalFee = 1;
            refundFee = 1;
        }
        wxPay.refund(order.getOrderSn(), refundNo, totalFee, refundFee, "拼团退款");

        OmsOrder expiredOrder = new OmsOrder();
        expiredOrder.setId(order.getId());
        expiredOrder.setStatus(4);
        orderMapper.updateByPrimaryKeySelective(expiredOrder);
    }

    @Override
    public List<OmsOrderGroupBuyDto> getOrderGroupList( OrderGroupParam orderGroupParam) {
        UmsMember member = memberService.getCurrentMember();
        List<OmsOrderGroupBuy> orderGroupBuyList = portalOrderBuyDao.queryListByMemberId(member.getId(), orderGroupParam);
        List<OmsOrderGroupBuyDto> orderGroupBuyDtoList = mapperFacade.mapAsList(orderGroupBuyList, OmsOrderGroupBuyDto.class).stream().map(dto ->{
            dto.setCreateTimeTxt(DateTimeHelper.getEpochTimeToString(dto.getCreateTime(), DateTimeHelper.SQL_DATETIME));
            dto.setExpiredTimeTxt(DateTimeHelper.getEpochTimeToString(dto.getExpiredTime(), DateTimeHelper.SQL_DATETIME));
            return dto;
        }).collect(Collectors.toList());
        return orderGroupBuyDtoList;
    }

    public static ConfirmOrderResult.CalcAmount calcCartAmount(CartPromotionItem omsCartItem)
    {
        ConfirmOrderResult.CalcAmount calcAmount = new ConfirmOrderResult.CalcAmount();
        calcAmount.setFreightAmount(new BigDecimal(0).setScale(2));
        calcAmount.setPayAmount(omsCartItem.getPrice().multiply(new BigDecimal(omsCartItem.getQuantity()).setScale(2)));
        calcAmount.setPromotionAmount(new BigDecimal(0).setScale(2));
        calcAmount.setTotalAmount(new BigDecimal(0).setScale(2));

        return calcAmount;
    }

    private OmsOrderItem buildGroupOrderItem(OmsGroupCartItem groupCartItem)
    {
        OmsOrderItem orderItem = new OmsOrderItem();
        orderItem.setProductId(groupCartItem.getProductId());
        orderItem.setProductName(groupCartItem.getProductName());
        orderItem.setProductPic(groupCartItem.getProductPic());
        orderItem.setProductAttr(groupCartItem.getProductAttr());
        orderItem.setProductBrand(groupCartItem.getProductBrand());
        orderItem.setProductSn(groupCartItem.getProductSn());
        orderItem.setProductPrice(groupCartItem.getPrice());
        orderItem.setProductQuantity(groupCartItem.getQuantity());
        orderItem.setProductSkuId(groupCartItem.getProductSkuId());
        orderItem.setProductSkuCode(groupCartItem.getProductSkuCode());
        orderItem.setProductCategoryId(groupCartItem.getProductCategoryId());
        orderItem.setPromotionAmount(new BigDecimal(0));
        orderItem.setPromotionName("团购");
        orderItem.setGiftIntegration(0);
        orderItem.setGiftGrowth(0);
        orderItem.setSp1(groupCartItem.getSp1());
        orderItem.setSp2(groupCartItem.getSp2());
        return orderItem;
    }
    private OmsOrder buildGroupOrder(UmsMember currentMember, OrderParam orderParam, BigDecimal totalAmount)
    {
        OmsOrder order = new OmsOrder();
        order.setDiscountAmount(new BigDecimal(0));
        order.setTotalAmount(totalAmount);
        order.setFreightAmount(new BigDecimal(0));
        order.setPromotionAmount(new BigDecimal(0));
        order.setPromotionInfo("团购");
        order.setCouponAmount(new BigDecimal(0));
        order.setIntegration(0);
        order.setIntegrationAmount(new BigDecimal(0));

        order.setPayAmount(totalAmount);
        //转化为订单信息并插入数据库
        order.setMemberId(currentMember.getId());
        order.setCreateTime(new Date());
        String nickName = StringUtils.isEmpty(currentMember.getNickname()) ? "" : currentMember.getNickname();
        try {
            order.setMemberUsername(URLEncoder.encode(nickName, "utf-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //支付方式：0->未支付；1->支付宝；2->微信
        order.setPayType(2);
        //订单来源：0->PC订单；1->app订单
        order.setSourceType(1);
        //订单状态：0->待付款；1->待发货；2->已发货；3->已完成；4->已关闭；5->无效订单
        order.setStatus(0);
        //订单类型：0->正常订单；1->秒杀订单
        order.setOrderType(1);
        //收货人信息：姓名、电话、邮编、地址
        UmsMemberReceiveAddress address = memberReceiveAddressService.getItem(orderParam.getMemberReceiveAddressId());
        order.setReceiverName(address.getName());
        order.setReceiverPhone(address.getPhoneNumber());
        order.setReceiverPostCode(address.getPostCode());
        order.setReceiverProvince(address.getProvince());
        order.setReceiverCity(address.getCity());
        order.setReceiverRegion(address.getRegion());
        order.setReceiverDetailAddress(address.getDetailAddress());
        order.setNote(orderParam.getContent());
        //0->未确认；1->已确认
        order.setConfirmStatus(0);
        order.setDeleteStatus(0);
        //计算赠送积分
        order.setIntegration(0);
        //计算赠送成长值
        order.setGrowth(0);
        //生成订单号
        order.setOrderSn(portalOrderService.generateOrderSn(order));
        return order;
    }

    public OmsOrderGroupBuy insertOrderGroupBuy(Long productGroupId, OmsOrder order, OmsOrderItem omsOrderItem, UmsMember currentMember, PmsProductGroupBuy pmsProductGroupBuy)
    {
        PmsSkuStock skuStock = skuStockMapper.selectByPrimaryKey(omsOrderItem.getProductSkuId());
        int activeSecond = pmsProductGroupBuy.getActiveHour() * 60;
        OmsOrderGroupBuy orderGroupBuy = OmsOrderGroupBuy.builder()
                .productGroupId(productGroupId)
                .productId(omsOrderItem.getProductId())
                .productName(omsOrderItem.getProductName())
                .pic(omsOrderItem.getProductPic())
                .skuId(omsOrderItem.getProductSkuId())
                .skuPrice(skuStock.getPrice())
                .groupPrice(omsOrderItem.getProductPrice())
                .ownerId(currentMember.getId())
                .nickname(currentMember.getNickname())
                .icon(currentMember.getIcon())
                .status(0)
                .memberCount(0)
                .createTime(DateTimeHelper.getEpochTimeInSecond(System.currentTimeMillis()))
                .expiredTime(DateTimeHelper.getEpochTimeInSecond(System.currentTimeMillis()) + activeSecond)
                .build();
        orderGroupBuyMapper.insert(orderGroupBuy);

        OmsOrderGroupBuyItem omsOrderGroupBuyItem = OmsOrderGroupBuyItem.builder()
                .omsOrderGroupBuyId(orderGroupBuy.getId())
                .memberId(currentMember.getId())
                .nickname(currentMember.getNickname())
                .icon(currentMember.getIcon())
                .orderId(order.getId())
                .createTime(DateTimeHelper.getEpochTimeInSecond(System.currentTimeMillis()))
                .build();
        orderGroupBuyItemMapper.insert(omsOrderGroupBuyItem);

        return orderGroupBuy;
    }


    OmsOrderGroupBuy updateOrderGroupBuy(Long orderGroupId, OmsOrder order, UmsMember currentMember, PmsProductGroupBuy pmsProductGroupBuy)
    {
        OmsOrderGroupBuy orderGroupBuy = orderGroupBuyMapper.selectByPrimaryKey(orderGroupId);
        if(null == orderGroupBuy)
        {
            throw new ServiceException("当前团购不存在");
        }

        OmsOrderGroupBuyItem omsOrderGroupBuyItem = OmsOrderGroupBuyItem.builder()
                .omsOrderGroupBuyId(orderGroupId)
                .memberId(currentMember.getId())
                .nickname(currentMember.getNickname())
                .icon(currentMember.getIcon())
                .orderId(order.getId())
                .createTime(DateTimeHelper.getEpochTimeInSecond(System.currentTimeMillis()))
                .build();
        orderGroupBuyItemMapper.insert(omsOrderGroupBuyItem);

        return orderGroupBuy;
    }

    private void inActiveNoPaymentOrder(Long orderBuyId)
    {
        OmsOrderGroupBuyItemExample omsOrderGroupBuyItemExample = new OmsOrderGroupBuyItemExample();
        omsOrderGroupBuyItemExample.createCriteria().andOmsOrderGroupBuyIdEqualTo(orderBuyId);
        List<OmsOrderGroupBuyItem> orderGroupBuyItemList = orderGroupBuyItemMapper.selectByExample(omsOrderGroupBuyItemExample);

        for(OmsOrderGroupBuyItem item : orderGroupBuyItemList)
        {
            if(item.getStatus().equals(OrderGroupStatus.EMPTY_ORDER.value))
            {
                OmsOrder omsOrder = orderMapper.selectByPrimaryKey(item.getOrderId());
                if(null != omsOrder)
                {
                    omsOrder.setStatus(4);
                    orderMapper.updateByPrimaryKeySelective(omsOrder);
                }
                orderGroupBuyItemMapper.deleteByPrimaryKey(item.getId());
            }
        }
    }


    public enum OrderGroupStatus {
        EMPTY_ORDER(0),
        INPROGESS_ORDER(1),
        COMPLATED(2),
        INACTIVE(3);
        Integer value;

        OrderGroupStatus(Integer value)
        {
            this.value = value;
        }

    }
}
